package main

import "fmt"

//输入: s = "PAYPALISHIRING", numRows = 3
//输出: "PAHNAPLSIIGYIR"
//
//P   A   H   N
//A P L S I I G
//Y   I   R

//0 4 8  12
//135791113
//2 6 10
//输入: s = "PAYPALISHIRING", numRows = 4
//输出: "PINALSIGYAHRPI"
//解释:
//
//P     I     N
//A   L S   I G
//Y A   H R
//P     I
//0   6    12
//1 5 7 11 13
//2 4 8 10
//3   9
func main() {
	//s, rows := "PAYPALISHIRING", 3
	//str := convert(s, rows)
	//s, rows := "PAYPALISHIRING", 4
	//str := convert(s, rows)
	s, rows := "ABCDE", 4
	str := convert(s, rows)
	fmt.Println(str)
}

// 主要思路是普通情况是按照余数插入数组，中间转弯使用for 循环到插入数组，要注意索引out
func convert(s string, numRows int) string {
	var arr []string

	for i := 0; i < numRows; i++ {
		arr = append(arr, "")
	}

	num := 0
	for i := 0; i < len(s); i++ {
		v := num % numRows
		mid := numRows - 2
		num++

		// 处理中间情况
		if num > numRows && num <= numRows+mid {
			num = 0
			for j := mid; j > 0; j-- {
				arr[j] += string(s[i])
				i++
				// 处理索引超出
				if i>=len(s){
					break
				}
			}
			i-- // 必须减去一次
		} else {
			arr[v] += string(s[i])
		}

	}

	result := ""
	for _, v := range arr {
		result += v
	}
	return result
}
